import {
  wxRequest
} from '../../utils/server.js';
const _wxRequest = new wxRequest();
let util = require('../../utils/util.js');
let moment = require('../../utils/moment.js');
const app = getApp()
Page({
  data: {
    imgUrl: app.globalData.imgUrl,
    coverImgsnum: 6,
    cententDetail: {},
    coverVideo: '', // '/org/StoreVO/2019/11/19/VAX0EIQuSjGCIt4NCEOQzw.mp4',
    uploadUrl: wx.getStorageSync('uploadUrl'),
    isIphoneX: app.globalData.isIphoneX,
    coverImgs: [],
    extraNodes: [{
      type: "after",
      dragId: "plus",
      slot: "plus",
      fixed: true
    }],
    pageMetaScrollTop: 0,
    scrollTop: 0,

    infoList: [{
      name: '图片',
      infoindex: 0,
      id: 1
    },
    {
      name: '视频',
      infoindex: 1,
      id: 2
    }
    ],
    infoindex: 0,

    categoryList: [],
    categoryindex: 0,

    isEdit: false,
    isDelImg: false,
    isDelVideo: false,
    orgType: '',

    devTypeList: [],
    devIndex: 0,
    id: '',

    catId: 0,
    
    frontImg:"",

    zhutuCoverImgs: [],
  },


  onLoad: function (options) {
    this.dragcoverImgs = this.selectComponent('#dragcoverImgs');
    this.dragcoverImgs.init();
    this.contentVideo = this.selectComponent("#contentVideo")

    this.dragcoverImgszhutu = this.selectComponent('#dragcoverImgszhutu');
    this.dragcoverImgszhutu.init();

    if (options.id) {
      this.setData({
        id: options.id
      })
      // 编辑
      this.handleEditData()
    }
    // 获取分类
    this.getCategory()
    this.getDeviceTypeVO();//获取设备类型
  },

  onShow: function () {
    this.setData({
      orgType: wx.getStorageSync('userInfo').orgType
    })
  },

  onUnload: function () {
    wx.removeStorageSync('noteItem')
  },

  onHide: function () {
    wx.removeStorageSync('noteItem')
  },

  handleEditData: function () {
    let noteItem = wx.getStorageSync('noteItem')
    if (wx.getStorageSync('noteItem')) {
      console.log('noteItem', noteItem);
      let infoindex = Number(noteItem.logType) - 1
      this.data.cententDetail = noteItem
      let list = []
      let zhutuCoverImgs = []
      let frontImg = null
      let contentVideo =null

      const imgJson = JSON.parse(noteItem.imgJson)
      if (noteItem.logType == 1) {
        // 图文
        // this.data.coverImgs
        imgJson.forEach((item, index) => {
          list.push({})
          list[index]['imgName'] = item.fileName
          //list[index]['imgPath'] = item.filePath.split('uploads/zmg')[1]
          list[index]['imgPath'] = item.filePath
          list[index]['fixed'] = false
          
          const imgObj = { imgName: noteItem.imgName, imgPath: noteItem.imgPath, fixed: false }
          zhutuCoverImgs.push(imgObj)
        })
        //this.data.coverImgs = list
      } else {
        if(noteItem.imgPath.indexOf('mp4') == -1){
          const imgObj = { imgName: noteItem.imgName, imgPath: noteItem.imgPath, fixed: false }
          zhutuCoverImgs.push(imgObj)
        }
        // 视频
        frontImg = imgJson[0].filePath
        contentVideo = frontImg
      }

      this.setData({
        isEdit:true,
        infoindex,
        logType: noteItem.logType,
        cententDetail: this.data.cententDetail,
        frontImg,
        coverImgs: list,
        contentVideo,
        catId: noteItem.catId,
        zhutuCoverImgs
      })
    }
  },

  deleteImg: function (e) {
    this.data.cententDetail.imgPath = ''
    this.data.frontImg = ''
    this.setData({
      isDelImg: true,
      frontImg: ''
    })
  },

  //介绍视频回调
  contentVideoCallback: function () {
    console.log('this.contentVideo.data.video', this.contentVideo.data.video)
    this.setData({
      contentVideo: this.contentVideo.data.video,
      contentVideoTime: '00:' + this.contentVideo.data.duration,
    })
  },

  // 获取分类
  getCategory() {
    _wxRequest.wxTonkenAjax({
      url: app.globalData.apiUrl + '/com/protected/vlog/findCategory',
      method: 'POST',
      data: {

      }
    }, (res) => {
      let result = res.list.filter(item => item.level == 1)
      let categoryList = []
      result.forEach((item, index) => {
        categoryList.push({
          name: item.catName,
          id: item.id,
          categoryindex: index,
          auth: item.auth
        })
      })

      if (this.data.id) {
        const categoryindex = categoryList.findIndex(e => this.data.catId == e.id)
        this.setData({ categoryindex })
      }
      let catId = this.data.catId || (categoryList.length > 0 ? categoryList[0].id : '')
      this.setData({
        categoryList: categoryList,
        catId: catId
      })
    })
  },

  categoryPickerChange: function (e) {
    var categoryindex = e.detail.value;
    var categoryList = this.data.categoryList
    var catId = '';

    categoryList.map((item, index) => {
      if (index == categoryindex) {
        catId = item.id
      }
    })
    console.log(catId)
    this.setData({
      categoryindex,
      catId
    })
  },

  //获取设备类型
  getDeviceTypeVO() {
    _wxRequest.wxTonkenAjax({
      url: app.globalData.apiUrl + '/gds/protected/device/findListForVlog',
      //url: app.globalData.apiUrl + '/gds/protected/dyeColor/findList',
      method: 'POST',
      data: {}
    }, (res) => {
      var list = res.list
      this.setData({
        devTypeList: list
      })
    })
  },

  // 设备类型
  devPickerChange: function (e) {
    console.log(e, 123123);
    var val = e.detail.value
    this.setData({
      devIndex: val
    })
  },

  //选择类型
  infoPickerChange: function (e) {
    var infoindex = e.detail.value;
    var infoList = this.data.infoList
    var logType = '';
    console.log(infoindex);

    infoList.map((item, index) => {
      if (index == infoindex) {
        logType = item.id
      }
    })
    console.log(logType);
    this.setData({
      infoindex,
      logType
    })
  },

  chooseGoodsImg: function (e) {
    this.setData({
      imgs: this.coverImgs.data.imgs,
      isHide: true
    })
  },

  deleteGoodsImg: function (e) {
    this.setData({
      imgs: this.coverImgs.data.imgs
    })
  },

  deloriginGoodsImg: function () {
    this.setData({
      originImgs: this.details.data.originImgs
    })
  },


  //表单提交
  formSubmit: function (e) {
    var formdata = e.detail.value;
    console.log(formdata.content);
    formdata.logType = this.data.logType || 1;
    // formdata.auth = formdata.auth ? 1 : 0;
    if (Number(this.data.logType) == 2) {
      console.log('this.data.contentVideo', this.data.contentVideo)
      let list = [{}]
      list[0]['fileName'] = this.data.contentVideo.split('/').filter(item => item.indexOf('.') != -1)[0].split('.')[0]
      list[0]['filePath'] = this.data.contentVideo
      formdata.fileList = list
      console.log(formdata.fileList, 1111);
      if (!formdata.fileList) {
        wx.showToast({
          icon: 'none',
          title: '请上传视频',
        })
        return
      }
    } else {
      let list = []
      console.log(this.data.coverImgs);
      this.data.coverImgs.forEach((item, index) => {
        list.push({})
        list[index]['fileName'] = item.imgName
        list[index]['filePath'] = item.imgPath
      })
      formdata.fileList = list
      if (formdata.fileList && formdata.fileList.length < 1) {
        wx.showToast({
          icon: 'none',
          title: '请上传笔记图片',
        })
        return
      }
    }

    formdata.catId = this.data.catId;
    if (!formdata.catId) {
      wx.showToast({
        icon: 'none',
        title: '请选择分类',
      })
      return
    }

    formdata.devTypeId = this.data.devTypeList[this.data.devIndex].id

    if (!formdata.content) {
      wx.showToast({
        icon: 'none',
        title: '请选择说明内容',
      })
      return
    }

    if (!formdata.title) {
      wx.showToast({
        icon: 'none',
        title: '标题不能为空',
      })
      return
    }
    console.log(formdata);

    if (this.data.zhutuCoverImgs.length > 0) {
      formdata.imgPath = this.data.zhutuCoverImgs[0].imgPath
      formdata.imgName = this.data.zhutuCoverImgs[0].imgName
    }
  

    this.formRequest(formdata);
  },




  //请求
  formRequest: function (formdata) {
    var url = '/com/protected/vlog/create';
    var title = "发布成功"
    //修改
    if (this.data.id) {
      url = '/com/protected/vlog/update';
      formdata.id = this.data.cententDetail.id;
      formdata.auditStatus = 0;
      title = "修改成功"
    }

    _wxRequest.wxTonkenAjax({
      url: app.globalData.apiUrl + url,
      method: 'POST',
      data: formdata
    }, (res) => {
      console.log(res)
      wx.showToast({
        title,
      })
      setTimeout(() => {
        wx.redirectTo({
          url: '/pages/square/list',
        })
      }, 1500)

    })
  },




  // 获取轮播图和介绍图片
  getImg: function () {
    var that = this
    _wxRequest.wxTonkenAjax({
      url: app.globalData.apiUrl + '/org/protected/comm/beanCrud/org.StoreImgVO/find',
      method: 'post',
      data: {
        stoId: this.data.id,
        pageSize: 100
      }
    }, (res) => {
      var coverImgs = []
      var list = res.list;
      list.map((item) => {
        coverImgs.push(item)
      })


      //拖拽coverImgs 
      if (coverImgs.length > 0) {
        coverImgs.map(item => {
          item.fixed = false
        })
      }


      that.setData({
        coverImgs: coverImgs
      })

      that.dragcoverImgs.init()
    })
  },

  //**************轮播拖拽**************
  sortEnd(e) {
    this.setData({
      coverImgs: e.detail.listData
    });
  },
  change(e) {
    this.setData({
      coverImgs: e.detail.listData
    });
    this.dragcoverImgs.init()
  },
  zhutuChange(e) {
    this.setData({
      zhutuCoverImgs: e.detail.listData
    });
    this.dragcoverImgszhutu.init()
  },
  sizeChange(e) {
    wx.pageScrollTo({
      scrollTop: 0
    })
    this.setData({
      size: e.detail.value
    });
    this.dragcoverImgs.init();
  },

  itemClick(e) {
    console.log(e);
  },
  toggleFixed(e) {
    let key = e.currentTarget.dataset.key;
    let {
      coverImgs
    } = this.data;
    coverImgs[key].fixed = !coverImgs[key].fixed
    this.setData({
      coverImgs: coverImgs
    });
    this.dragcoverImgs.init();
  },
  add(e) {
    let coverImgs = this.data.coverImgs;
    var that = this
    wx.chooseImage({
      count: that.data.coverImgsnum - that.data.coverImgs.length,
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        var tempFilePaths = res.tempFilePaths;
        that.uploadFile(res.tempFilePaths, 'coverImgs')
      }
    });
  },
  zhutuadd(e) {
    var that = this
    wx.chooseImage({
      count: that.data.coverImgsnum - that.data.coverImgs.length,
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        that.uploadFile(res.tempFilePaths, 'zhutuCoverImgs')
      }
    });
  },

  //上传图片
  uploadFile: function (pics, idName) {
    var that = this;
    var listData = this.data[idName]
    this.setData({
      loading: true
    })
    for (var i = 0; i < pics.length; i++) {
      (function (i) {
        //   setTimeout(function () { 
        wx.uploadFile({
          //url: app.globalData.apiUrl + '/org/protected/comm/file/org.StoreVO/fileUpload',
          url: app.globalData.apiUrl + '/com/comm/oss/upload',
          header: {
            "Authorization": wx.getStorageSync('Authorization'),
          },
          formData: {
            //width: 750,
            subfolder: 'image'
          },
          filePath: pics[i],
          name: 'file',
          success: function (res) {
            var resdata = res.data
            if (typeof res.data == "string") {
              resdata = JSON.parse(res.data)
            }
            if (resdata.success) {

              var item = {
                //imgName: resdata.datas.data.fileName,
                imgName: resdata.datas.data.originalFileName,
                imgPath: resdata.datas.data.url,
                fixed: false
              }
              listData.push(item)
              that.setData({
                [idName]: listData
              })

              //初始化组件
              if (idName == 'coverImgs') {
                that.dragcoverImgs.init();
              } else if (idName == 'contentImgs') {
                that.dragcontentImgs.init();
              } else if (idName == 'zhutuCoverImgs') {
                that.dragcoverImgszhutu.init();
              }
            } else {
              wx.showToast({
                icon: 'none',
                title: '图片上传失败',
              })
            }
            //最后一张关闭遮罩 
            console.log(i + 1 == pics.length, 'last')
            if (i + 1 == pics.length) {
              that.setData({
                loading: false
              })
            }

          },
          fail: function (res) {
            console.log(res)
            // wx.showToast({
            //   icon: 'none',
            //   title: '图片上传失败',
            // })
          }
        })
        //   }, (i + 1) * 800);
      })(i)
    }
  },

  scroll(e) {
    this.setData({
      pageMetaScrollTop: e.detail.scrollTop
    })
  },

  // 页面滚动
  onPageScroll(e) {
    this.setData({
      scrollTop: e.scrollTop
    });
  },


})